<script setup lang="tsx">
import { AddIcon } from 'tdesign-icons-vue-next';
import { Link, MessagePlugin, Space } from 'tdesign-vue-next';
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';

import { getGradeList } from '@/api/member/level';
import { add, Delete, edit, getInfo, getProductList } from '@/api/yuebao/product';
import { formGroup } from '@/components/formDialog/FormDialog';
import FormDialogGroup from '@/components/formDialog/FormDialogGroup.vue';
import MyTable from '@/components/myTable/index.vue';
import OperatingBox from '@/components/operatingBox/index.vue';
import TinymceEditor from '@/components/tinymceEditor/index.vue';
import UpLoad from '@/components/upLoad/index.vue';

const { t } = useI18n();

const data = ref([]);

const columns = [
  {
    title: '标题',
    colKey: 'title',
  },
  {
    title: '类型',
    colKey: 'type',
  },
  {
    title: '总利率(%)',
    colKey: 'lilv',
    cell: (h: any, { row }: { row: any }) => {
      return new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }).format(row.lilv || 0);
    },
  },
  {
    title: '时间(天)',
    colKey: 'time',
  },
  {
    title: '最低存储金额',
    colKey: 'min',
    cell: (h: any, { row }: { row: any }) => {
      return new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }).format(row.min || 0);
    },
  },
  {
    title: '最高存储金额',
    colKey: 'max',
    cell: (h: any, { row }: { row: any }) => {
      return new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }).format(row.max || 0);
    },
  },
  {
    title: '购买等级',
    colKey: 'vipLevel',
  },
  {
    title: '信用分',
    colKey: 'credit',
  },
  {
    title: '结束时间',
    colKey: 'endtime',
    width: 200,
  },
  {
    title: '购买次数限制',
    colKey: 'buytimes',
  },
  {
    title: '剩余(%)',
    colKey: 'surplus',
    cell: (h: any, { row }: { row: any }) => {
      return new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }).format(row.surplus || 0);
    },
  },
  {
    title: '排序',
    colKey: 'sort',
  },
  {
    title: '状态',
    colKey: 'state',
  },
  {
    title: '操作',
    colKey: 'op',
  },
];

const pagination = ref({
  defaultCurrent: 1,
  defaultPageSize: 10,
  total: 0,
});

const render = () => (
  <>
    <OperatingBox>
      <t-button icon={() => <AddIcon />} onClick={() => unAdd()}>
        新增
      </t-button>
    </OperatingBox>
    <MyTable
      columns={columns}
      data={data.value}
      v-model:pagination={pagination.value}
      rowKey="yid"
      onUnGetList={unGetList}
    >
      {{
        type: (slotProps: any) => (
          <div>{slotProps.row.type == '1' ? '初级' : slotProps.row.type == '2' ? '中级' : '高级'}</div>
        ),
        state: (slotProps: any) => (
          <t-switch
            key={slotProps.row.grade}
            value={slotProps.row.state}
            onChange={() => unEditState(slotProps)}
            size="large"
            customValue={[1, 0]}
            label={['开', '关']}
          ></t-switch>
        ),
        op: (slotProps: any) => (
          <Space>
            <Link theme="primary" onClick={() => unEdit(slotProps)}>
              修改
            </Link>
            <Link theme="danger" onClick={() => deleteClickOp(slotProps, false)}>
              {t('pages.detailCard.detail.form.delete')}
            </Link>
          </Space>
        ),
      }}
    </MyTable>
  </>
);

// 修改状态
const unEditState = async (slotProps: any) => {
  slotProps.row.state = slotProps.row.state == 1 ? 0 : 1;
  const vipLevel = slotProps.row.vipLevel.split(',');
  edit({ ...slotProps.row, vipLevel }).then(() => {
    MessagePlugin.success('操作成功');
    unGetList();
  });
};

// 等级列表
import { useGradeStore } from '@/store/modules/member';

const gradeStore = useGradeStore();
const gradeList = ref<any[]>([]);
gradeList.value = gradeStore.gradeList;

const unGetList = async () => {
  try {
    const res = await getProductList({
      pageNum: pagination.value.defaultCurrent,
      pageSize: pagination.value.defaultPageSize,
    });
    data.value = res.rows;
    pagination.value = {
      ...pagination.value,
      total: res.total,
    };
  } catch (e) {
    console.log(e);
  }
};
unGetList();

/** 添加对话框 */
const formObj = new formGroup();
const unAdd = async () => {
  try {
    formObj.show(
      '添加产品',
      {
        vipLevel: [],
      },
      '添加产品',
    );
  } catch (e) {
    console.error(e);
    MessagePlugin.error(e);
  }
};

formObj.add<any>(
  '添加产品',
  '添加产品',
  {},
  async (body) => {
    const data = {
      ...body.data,
    };
    data.state = 1;
    await add(data);
    unGetList();
  },
  {
    title: [{ required: true, message: '产品标题不能为空', trigger: 'blur' }],
    type: [{ required: true, message: '产品类型不能为空', trigger: 'blur' }],
    lilv: [{ required: true, message: '总利率不能为空', trigger: 'blur' }],
    time: [{ required: true, message: '时间不能为空', trigger: 'blur' }],
    sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
  },
  '40%',
);

// 详情
const unEdit = async (slotProps: any) => {
  try {
    const res = await getInfo(slotProps.row.yid);
    res.data.vipLevel = res.data.vipLevel.split(',');
    formObj.show(
      '编辑产品',
      {
        ...res.data,
      },
      '编辑产品',
    );
  } catch (e) {
    console.error(e);
    MessagePlugin.error(e);
  }
};

formObj.add<any>(
  '编辑产品',
  '编辑产品',
  {},
  async (body) => {
    await edit(body.data);
    unGetList();
  },
  {
    title: [{ required: true, message: '产品标题不能为空', trigger: 'blur' }],
    type: [{ required: true, message: '产品类型不能为空', trigger: 'blur' }],
    lilv: [{ required: true, message: '总利率不能为空', trigger: 'blur' }],
    time: [{ required: true, message: '时间不能为空', trigger: 'blur' }],
    sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
  },
  '40%',
);

// 删除
const confirmVisible = ref(false);
const deleteId = ref([]);
const onConfirmDelete = () => {
  const ids = deleteId.value.join(',');
  Delete(ids).then(() => {
    confirmVisible.value = false;
    MessagePlugin.success('删除成功');
    unGetList();
  });
};

const deleteClickOp = (value: any, isSingle: boolean) => {
  if (isSingle && !value.length) {
    MessagePlugin.warning('请先勾选数据');
    return;
  }
  confirmVisible.value = true;
  deleteId.value = isSingle ? value : [value.row.yid];
};
</script>

<template>
  <div>
    <render />
    <form-dialog-group :form-obj="formObj">
      <template #default="{ formData, item }">
        <!-- 添加产品对话框 -->
        <template v-if="item == '添加产品' || item == '编辑产品'">
          <t-form-item label="标题" name="title">
            <t-input v-model="formData.title" placeholder="请输入标题" />
          </t-form-item>
          <t-form-item label="类型" name="type">
            <t-select v-model="formData.type" placeholder="请选择类型">
              <t-option key="1" label="初级" value="1" />
              <t-option key="2" label="中级" value="2" />
              <t-option key="3" label="高级" value="3" />
            </t-select>
          </t-form-item>
          <t-form-item label="总利率(%)" name="lilv" help="如：50">
            <div class="capital">
              <t-input-number v-model="formData.lilv" placeholder="请输入总利率" />
            </div>
          </t-form-item>
          <t-form-item label="时间(天)" name="time" help="如：10">
            <div class="capital">
              <t-input-number v-model="formData.time" placeholder="请输入时间" />
            </div>
          </t-form-item>
          <t-form-item label="最低存储金额" name="min" help="如：100">
            <div class="capital">
              <t-input-number v-model="formData.min" placeholder="请输入最低存储金额" />
            </div>
          </t-form-item>
          <t-form-item label="最高存储金额" name="max" help="如：100">
            <div class="capital">
              <t-input-number v-model="formData.max" placeholder="请输入最高存储金额" />
            </div>
          </t-form-item>
          <t-form-item label="购买等级" name="vipLevel">
            <t-checkbox-group v-model="formData.vipLevel">
              <t-checkbox key="all" :check-all="true" label="全选" />
              <t-checkbox v-for="item in gradeList" :key="item.grade" :label="item.name" :value="item.grade" />
            </t-checkbox-group>
          </t-form-item>
          <t-form-item label="信用分" name="credit" help="达到多少信用分可购买，0或不填表示不限制">
            <div class="capital">
              <t-input-number v-model="formData.credit" placeholder="请输入信用分" />
            </div>
          </t-form-item>
          <t-form-item label="购买次数" name="buytimes" help="0或不填表示不限制">
            <div class="capital">
              <t-input-number v-model="formData.buytimes" placeholder="请输入购买次数" />
            </div>
          </t-form-item>
          <t-form-item label="排序" name="sort">
            <div class="capital">
              <t-input-number v-model="formData.sort" placeholder="请输入排序" />
            </div>
          </t-form-item>
          <t-form-item label="剩余(%)" name="surplus">
            <div class="capital">
              <t-input-number v-model="formData.surplus" />
            </div>
          </t-form-item>
          <t-form-item label="结束时间" name="endtime">
            <t-date-picker
              v-model="formData.endtime"
              enable-time-picker
              :style="{ width: '314px' }"
              allow-input
              clearable
              placeholder="请选择结束时间"
            />
          </t-form-item>
          <t-form-item label="产品简介" name="introduction">
            <t-textarea v-model="formData.introduction" placeholder="产品简介" :autosize="{ minRows: 3 }" />
          </t-form-item>
          <t-form-item label="产品图标" name="image">
            <up-load :key="formData.image" v-model:image="formData.image"></up-load>
          </t-form-item>
          <t-form-item label="产品说明" name="description">
            <tinymce-editor ref="editor" v-model="formData.description"></tinymce-editor>
          </t-form-item>
        </template>
      </template>
    </form-dialog-group>
    <t-dialog
      v-model:visible="confirmVisible"
      header="确认删除当前所选项目？"
      body="删除后，数据将被清空，且无法恢复"
      @confirm="onConfirmDelete"
    />
  </div>
</template>

<style lang="less" scoped>
.capital .t-input-number.t-input-number--row {
  width: 314px;
  display: flex;
  align-items: center;
  padding: 0 38px;

  .t-button.t-button--variant-outline.t-button--theme-default.t-button--shape-square.t-button--icon-only {
    width: 38px;
    height: 38px;
  }
}
</style>
<style>
.capital .t-input-number .t-input.t-align-center {
  width: 230px !important;
}
</style>
